package cn.haohaowo.service.impl;


import cn.haohaowo.common.Constants;
import cn.haohaowo.common.Page;
import cn.haohaowo.entity.Order;
import cn.haohaowo.service.OrderBizService;
import cn.haohaowo.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderBizServiceImpl implements OrderBizService {


	@Autowired(required = false)
	private RestTemplate restTemplate;


	public boolean createOrder(Order order) {

		String url = Constants.RESTFUL_URL + "order/saveOrder";
		MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
		para.set("orderJSON", order);
		String result = restTemplate.postForObject(url, para, String.class);
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObject = JSONObject.parseObject(result);
			Boolean isSuccess = jsonObject.getBoolean("isSuccess");
			return isSuccess;
		}

		return false;

	}

//	public long getCurrentAccountCompletedOrdersCount(Integer accountId) {
//		return orderDao.getCompletedOrdersCount(accountId);
//	}
//
//	public long getCurrentAccountOnPrecessingOrdersCount(Integer accountId) {
//		return orderDao.getOnPrecessingOrdersCount(accountId);
//	}

	public Page<Order> getCurrentAccountOrders(int accountId, int pageNo) {
		
		return getCurrentAccountOrders(accountId, pageNo, Constants.PAGE_SIZE);

	}

	public Page<Order> getCurrentAccountOrders(int accountId, int pageNo, int pageSize) {

		String url = Constants.RESTFUL_URL + "order/queryOrders";
		MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
		para.set("accountId", accountId);
		para.set("pageNo", pageNo);
		para.set("pageSize", pageSize);
		String result = restTemplate.postForObject(url, para, String.class);
		if (StringUtils.isNotEmpty(result)) {
			Page<Order> bookPage = JSONObject.parseObject(result, Page.class);
			return bookPage;
		}

		return null;

	}

	public Order getOrder(int orderId) {

		String url = Constants.RESTFUL_URL + "order/queryOrderById";
		MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
		para.set("orderId", orderId);
		String result = restTemplate.postForObject(url, para, String.class);
		if (StringUtils.isNotEmpty(result)) {
			Order order = JSONObject.parseObject(result, Order.class);
			return order;
		}

		return null;

	}

}
